package com.atguigu.gmall.wms.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.wms.mapper.WareSkuMapper;
import com.atguigu.gmall.wms.vo.SkuLockVo;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author: 86182
 * @Date: 2021/8/26
 * @Time: 0:41
 * @Version:
 */
@Component
public class StockListener {
    private static final String KEY_PREFIX = "stock:info:";
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private WareSkuMapper wareSkuMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("WARE_UNLOCK_QUEUE"),
            exchange = @Exchange(value = "ORDER_EXCHANGE", ignoreDeclarationExceptions = "true", type = ExchangeTypes.TOPIC),
            key = "stock.unlock"
    ))
    public void unlock(String orderToekn, Channel channel, Message message) throws IOException {
        if (StringUtils.isBlank(orderToekn)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            return;
        }
        // 1. 根据orderToken获取库存的锁定信息
        String json = this.redisTemplate.opsForValue().get(KEY_PREFIX + orderToekn);
        // 2.判空,为空直接确认消息
        if (StringUtils.isBlank(json)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            return;
        }
        List<SkuLockVo> skuLockVos = JSON.parseArray(json, SkuLockVo.class);
        if (CollectionUtils.isEmpty(skuLockVos)){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            return;
        }
        // 3.遍历锁定库存信息,解锁库存
        skuLockVos.forEach(skuLockVo -> {
            this.wareSkuMapper.unlockStock(skuLockVo.getWareSkuId(),skuLockVo.getCount());
        });
        // 4.删除redis中缓存的锁定库存信息
        this.redisTemplate.delete(KEY_PREFIX + orderToekn);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}












